package com.example.tms.controller;

import com.example.tms.bean.ReturnInfo;
import com.example.tms.bean.UserInfo;
import com.example.tms.bean.UserView;
import com.example.tms.mapper.PermsVMapper;
import com.example.tms.mapper.UserMapper;
import com.example.tms.mapper.UserVMapper;
import com.example.tms.tools.GlobalParam;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * 用户信息
 */
@RestController
public class UserController {

    private final UserMapper userMapper;
    private final UserVMapper userVMapper;
    private final PermsVMapper permsVMapper;

    @Autowired
    public UserController(UserMapper userMapper, UserVMapper userVMapper, PermsVMapper permsVMapper) {
        this.userMapper = userMapper;
        this.userVMapper = userVMapper;
        this.permsVMapper = permsVMapper;
    }

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //查询个人权限
    @RequestMapping(value = "permission",method = RequestMethod.GET)
    public ReturnInfo getUserPerms(){
        Subject subject = SecurityUtils.getSubject();
        UserView userView = (UserView) subject.getPrincipal();
        System.out.println("查询个人权限");
        return ReturnInfo.info2(permsVMapper.findByYhid(userView.getYhid()));
    }

    //查询用户信息(用户id)
    @RequestMapping(value = "user/{yhid}",method = RequestMethod.GET)
    public UserView getUserInfo(@PathVariable String yhid){
        return userVMapper.findByYhid(yhid);
    }

    //查询当前用户信息
    @RequestMapping(value = "currentUser",method = RequestMethod.GET)
    public UserView getCurrentUser(){
        Subject subject = SecurityUtils.getSubject();
        return (UserView) subject.getPrincipal();
    }

    //查询用户信息列表
    @RequestMapping(value = "user",method = RequestMethod.GET)
    public ReturnInfo getUserInfoAll(@RequestParam(required = false, defaultValue = "") String yhm,
                                     @RequestParam(required = false, defaultValue = "") String zsxm,
                                     @RequestParam(required = false, defaultValue = "") String name){
        List<UserView> result = userVMapper.findAll((Root<UserView> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            if(!yhm.equals("")){
                list.add(criteriaBuilder.like(root.get("yhm").as(String.class),"%" + yhm + "%"));
            }
            if(!zsxm.equals("")){
                list.add(criteriaBuilder.like(root.get("zsxm").as(String.class),"%" + zsxm + "%"));
            }
            if(!name.equals("")){
                list.add(criteriaBuilder.like(root.get("name").as(String.class),"%" + name + "%"));
            }
            list.add(criteriaBuilder.equal(root.get("sfcz").as(Boolean.class),true));
            Predicate[] p = new Predicate[list.size()];
            criteriaQuery.where(criteriaBuilder.and(list.toArray(p)));
            criteriaQuery.orderBy(criteriaBuilder.desc(root.get("lasttime")));
            return criteriaQuery.getRestriction();
        });
        return ReturnInfo.info2(result);
    }

    //新建用户信息
    @RequestMapping(value = "user",method = RequestMethod.POST)
    public List<Map<String,Object>> saveUserInfo(@RequestBody UserInfo userInfo) throws NoSuchAlgorithmException {
        List<Map<String,Object>>  list = new ArrayList<>();
        Map<String,Object>  map = new HashMap<>();
        if(userInfo.getYhm().equals("")){
            map.put("yhm", "0");
        }else if(userMapper.findByYhm(userInfo.getYhm())!=null){
            map.put("yhm", "2");//用户名已存在
        }
        if(userInfo.getZsxm().equals("")||!checkName(userInfo.getZsxm())){
            map.put("zsxm", "0");
        }
        if(userInfo.getSjh().equals("")||!checkSjh(userInfo.getSjh())){
            map.put("sjh", "0");
        }
        if(userInfo.getBumenid()==null){
            map.put("bumenid", "0");
        }
        list.add(map);
        if(map.isEmpty()){
            userInfo.setZcsj(GlobalParam.getTime());
            userInfo.setLasttime(GlobalParam.getTime());
            userInfo.setSfcz(true);
            String sj = userInfo.getSjh();//密码设为手机后六位

            if(userInfo.getMima() == null || userInfo.getMima().equals("")){

                userInfo.setMima(GlobalParam.getMD5(sj.substring(sj.length()-6, sj.length())));
            }

            userMapper.save(userInfo);
            logger.info("新建用户"+userInfo.toString());
        }
        return list;
    }

    //更新用户信息
    @RequestMapping(value = "user",method = RequestMethod.PUT)
    public List<Map<String,Object>> updateUserInfo(@RequestBody UserInfo userInfo) throws NoSuchAlgorithmException {
        List<Map<String,Object>>  list = new ArrayList<>();
        Map<String,Object>  map = new HashMap<>();
        if(userInfo.getYhid().equals("")||userMapper.findByYhid(userInfo.getYhid())==null){
            map.put("yhid", "0");//该用户不存在
        }
        UserInfo olduser = userMapper.findByYhid(userInfo.getYhid());
        if(!userInfo.getYhm().equals(olduser.getYhm())&&userMapper.findByYhm(userInfo.getYhm())!=null) {
            map.put("yhm", "2");//用户名已存在
        }else if(userInfo.getYhm().equals("")){
            map.put("yhm", "0");
        }
        if(userInfo.getZsxm().equals("")||!checkName(userInfo.getZsxm())){
            map.put("zsxm", "0");
        }
        if(userInfo.getSjh().equals("")||!checkSjh(userInfo.getSjh())){
            map.put("sjh", "0");
        }
        if(userInfo.getBumenid()==null){
            map.put("bumenid", "0");
        }
        list.add(map);
        if(map.isEmpty()){
            userInfo.setZcsj(userMapper.findByYhid(userInfo.getYhid()).getZcsj());
            userInfo.setLasttime(GlobalParam.getTime());
            userInfo.setSfcz(true);
            String sj = userInfo.getSjh();//密码设为手机后六位
            if(userInfo.getMima() == null || userInfo.getMima().equals("")){
                userInfo.setMima(GlobalParam.getMD5( sj.substring(sj.length()-6, sj.length())));
            }
            userMapper.saveAndFlush(userInfo);
            logger.info("更新用户"+userInfo.toString());
        }
        return list;
    }

    //删除用户信息（假删除 用户id）
    @RequestMapping(value = "user/{yhid}",method = RequestMethod.DELETE)
    public ReturnInfo deleteUserinfo(@PathVariable String yhid){
        String b;
        if(yhid==null||userMapper.findByYhid(yhid)==null){
            b = "该用户不存在！";
        }else{
            userMapper.DeleteByYhid(yhid);
            b = "删除成功！";
            logger.info("删除用户"+yhid);
        }
        return ReturnInfo.info1(b);
    }

    //检查手机号码格式
    private Boolean checkSjh(String sjh){
        Boolean b = false;
        if(sjh.matches("^1[0-9 ]{10,12}$")){
            b = true;
        }
        return b;
    }

    //检查真实姓名格式
    private Boolean checkName(String  zsxm){
        Boolean b = false;
        if(zsxm.matches("^[\\u4E00-\\u9FA5A-Za-z]+$")){
            b = true;
        }
        return b;
    }
}
